package com.thinkerwu.xxljob.demo.config;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.executor.XxlJobExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * @author wuss45
 * @date 2018年10月16日-19时43分
 */

@Configuration
public class XxlJobConfig implements InitializingBean {

    private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @Value("${xxl.job.executor.appname}")
    private String appName;

    @Value("${xxl.job.executor.ip}")
    private String ip;

    @Value("${xxl.job.executor.port}")
    private int port;

    @Value("${xxl.job.accessToken}")
    private String accessToken;

    @Value("${xxl.job.executor.logpath}")
    private String logPath;

    @Value("${xxl.job.executor.logretentiondays}")
    private int logRetentionDays;

    @Value("${xxl.job.groupTitle}")
    private String groupTitle;

    private int groupId;


    @Bean(initMethod = "start", destroyMethod = "destroy")
    public XxlJobExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobExecutor xxlJobExecutor = new XxlJobExecutor();
        xxlJobExecutor.setAdminAddresses(adminAddresses);
        xxlJobExecutor.setAppName(appName);
        xxlJobExecutor.setIp(ip);
        xxlJobExecutor.setPort(port);
        xxlJobExecutor.setAccessToken(accessToken);
        xxlJobExecutor.setLogPath(logPath);
        xxlJobExecutor.setLogRetentionDays(logRetentionDays);

        return xxlJobExecutor;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        ReturnT<String> returnT;
        returnT = template.getForObject(adminAddresses.concat("/jobgroup/getGroupId?appName=").concat(appName), ReturnT.class);
        if (returnT == null || StringUtils.isEmpty(returnT.getContent())) {

            MultiValueMap<String, String> jobGroup = new LinkedMultiValueMap<>();
            jobGroup.add("appName", this.appName);
            jobGroup.add("title", this.groupTitle);
            jobGroup.add("order", Integer.toString(1));
            jobGroup.add("addressType", Integer.toString(0));

            HttpHeaders headers = new HttpHeaders();
            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(jobGroup, headers);

            returnT = template.postForObject(adminAddresses.concat("/jobgroup/save"), httpEntity, ReturnT.class);
        }
        this.groupId = Integer.valueOf(returnT.getContent());
    }

    public int getGroupId() {
        return groupId;
    }

    public String getAdminAddresses() {
        return adminAddresses;
    }
}
